//
//  MLAEateryShopInfoVC.m
//  MagicLampApp
//
//  Created by Zheng on 2019/4/12.
//  Copyright © 2019 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAEateryShopInfoVC.h"
#import "MLABaseFieldModel.h"
#import "MLABaseFieldView.h"
#import "MLASavePinCateVC.h"
#import "MLAChoosePhotosView.h"
#import <TZImagePickerController.h>

@interface MLAEateryShopInfoVC () <TZImagePickerControllerDelegate>

@end

@implementation MLAEateryShopInfoVC{
    NSArray<MLABaseFieldModel *> *modelsArr;

    MLAChoosePhotosView *photosView;
    NSMutableArray *photosArr;
    NSMutableArray *uploadArr;
    NSString *files;

    NSMutableDictionary *params;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    files = @"";
    [self configTitle:@"店铺信息"];
    
    photosArr = [NSMutableArray array];
    uploadArr = [NSMutableArray array];
    
    [self addSubviewsInView];

    if (_model.business_license.length > 0) {
        [[[UIImageView alloc] init] sd_setImageWithURL:[NSURL URLWithString:_model.business_license] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (image) {
                photosView.imagesArr = @[image];
            }
        }];
    }

    NSArray *arrs = @[_model.shop_name,_model.shop_type_name,_model.person_average,[NSString stringWithFormat:@"%@%@%@%@",_model.province,_model.city,_model.area,_model.address],_model.content];
    for (int i = 0; i < 5; i++) {
        MLABaseFieldView *txf = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:14000+i];
        txf.inputText = arrs[i];
    }
    
}

#pragma mark - LoadData
- (void)loadUpImagesData {
    
    UIImage *image = [uploadArr lastObject];
    NSData *fileData = UIImageJPEGRepresentation(image, 0.5);
    NSDictionary *params = @{@"file":fileData};
    
    [MLAHttpManage uploadHostType:MLAHttpHostType_Api api:kUploadFiles params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self->files = [self->files stringByAppendingString:[NSString stringWithFormat:@",%@",response[@"file_url"]]];
        [self->uploadArr removeLastObject];
        if (self->uploadArr.count == 0) {
            [self loadAddBillData];
        } else {
            [self loadUpImagesData];
        }
    } failure:^{
        
    }];
}

- (void)loadAddBillData {
    
    [MLAHttpManage postHostType:MLAHttpHostType_Jinxiaocun api:kBillAdd params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^{
        
    }];
}


#pragma mark - Actions
- (void)commitBtnAction {


    
    NSString *content = [self getContentWithTag:14001];
    NSString *buyer = [self getContentWithTag:14002];
    NSString *checker = [self getContentWithTag:14003];
    NSString *price = [self getContentWithTag:14004];
    
    if (content.length == 0) {
        [MLAHudManage showMessage:@"请输入事项内容"];
        return;
    }
    
    if (buyer.length == 0) {
        [MLAHudManage showMessage:@"请输入持票人"];
        return;
    }
    
    if (checker.length == 0) {
        [MLAHudManage showMessage:@"请输入审核人"];
        return;
    }
    
    if (price.length == 0) {
        [MLAHudManage showMessage:@"请输入金额"];
        return;
    }
    
    if (photosArr.count == 0) {
        [MLAHudManage showMessage:@"请选择附件图片"];
        return;
    }
    
    params = [NSMutableDictionary dictionary];

    [params setObject:content forKey:@"title"];
    [params setObject:buyer forKey:@"holder"];
    [params setObject:checker forKey:@"check"];
    [params setObject:files forKey:@"file"];
    [params setObject:price forKey:@"money"];
    
    uploadArr = [photosArr mutableCopy];
    
    [self loadUpImagesData];
}

- (NSString *)getContentWithTag:(NSInteger)tag {
    MLABaseFieldView *fieldView = (MLABaseFieldView *)[self.tableView.tableHeaderView viewWithTag:tag];
    return fieldView.inputText;
}


- (void)addPhotosDidClick {
    TZImagePickerController *imagePickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVC.allowCrop = YES;
    imagePickerVC.allowPickingVideo = NO;
    imagePickerVC.allowPickingGif = NO;
    imagePickerVC.cropRect = CGRectMake(0, (CX_GetScreenHeight()-CX_GetScreenWidth())/2., CX_GetScreenWidth(), CX_GetScreenWidth()*0.74);
    [self presentViewController:imagePickerVC animated:YES completion:nil];
    
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        [self->photosArr addObject:photos[0]];
        self->photosView.imagesArr = [self->photosArr copy];
    }];
}

- (void)deletePhotosDidClickWithDeleteIndex:(NSInteger)index {
    [photosArr removeObjectAtIndex:index];
    photosView.imagesArr = [photosArr copy];
}


#pragma mark - Subviews
- (void)addSubviewsInView {
    
    modelsArr = [self getModelsArr];
    
    CGFloat height = 660;
    
    UIView *tableHeaderView = [[UIView alloc] init];
    tableHeaderView.backgroundColor = CX_GetColorHex(0xFCFCFC, 1);
    tableHeaderView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), height);
    
    [modelsArr enumerateObjectsUsingBlock:^(MLABaseFieldModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MLABaseFieldView *fieldView = [[MLABaseFieldView alloc] init];
        fieldView.tag = 14000+idx;
        fieldView.model = obj;
        [tableHeaderView addSubview:fieldView];
        
        if (idx == 0) {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(20);
                make.left.right.equalTo(tableHeaderView);
                make.height.mas_equalTo(85);
            }];
        } else {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                UIView *view = [tableHeaderView viewWithTag:14000+idx-1];
                make.left.right.height.equalTo(view);
                make.top.equalTo(view.mas_bottom);
            }];
        }
    }];
    
    photosView = [[MLAChoosePhotosView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewLayout alloc] init]];
    photosView.notSelect = YES;
    photosView.title = @"营业执照：";
    [tableHeaderView addSubview:photosView];
    [photosView mas_makeConstraints:^(MASConstraintMaker *make) {
        UIView *view = [tableHeaderView viewWithTag:14000+self->modelsArr.count-1];
        make.top.equalTo(view.mas_bottom);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(CX_GetXScale(105));
    }];
    @weakify(self);
    photosView.photosViewDidClickAdd = ^{
        @strongify(self);
        [self addPhotosDidClick];
    };
    photosView.photosViewDidClickDetele = ^(NSInteger index, NSInteger tag) {
        @strongify(self);
        [self deletePhotosDidClickWithDeleteIndex:index];
    };
    
    UIButton *commitBtn = [self getCommitButtonWithTitle:@"提交"];
    [commitBtn addTarget:self action:@selector(commitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    commitBtn.hidden = YES;
    [tableHeaderView addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self->photosView.mas_bottom).offset(30);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(40);
    }];
    
    
    self.tableView.tableHeaderView = tableHeaderView;
    [tableHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(CX_GetScreenWidth());
        make.height.mas_equalTo(height);
    }];
    
}

- (NSArray<MLABaseFieldModel *> *)getModelsArr {
    
    NSArray *infosArr = @[CX_GetFieldInfoDic(@"店铺名称：", @"输入店铺名称", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"门店分类：", @"输入门店分类", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"人均消费：", @"输入人均消费", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"商铺位置：", @"输入商铺位置", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"详细内容：", @"输入详细内容", @"30", @"0", @"1", @"0", @"")];
    return [[MLABaseFieldModel mj_objectArrayWithKeyValuesArray:infosArr] copy];
}



@end
